const axios = require('axios')

const querystring = require('querystring')

const crypto = require('crypto');

 function md5Hex(data) {
	const hash = crypto.createHash('md5');

	const update = buffer => {
		const inputEncoding = typeof buffer === 'string' ? 'utf8' : undefined;
		hash.update(buffer, inputEncoding);
	};

	if (Array.isArray(data)) {
		for (const element of data) {
			update(element);
		}
	} else {
		update(data);
	}

	return hash.digest('hex');
}



//请求url --正式地址
const Url = 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx'
//用户ID，快递鸟提供，注意保管，不要泄漏
const EBusinessID = '1721152';//即用户ID，登录快递鸟官网会员中心获取 https://www.kdniao.com/UserCenter/v4/UserHome.aspx 
//API key，快递鸟提供，注意保管，不要泄漏
const ApiKey = '640c3edb-a759-42d8-9900-245e83c3d723';//即API key，登录快递鸟官网会员中心获取 https://www.kdniao.com/UserCenter/v4/UserHome.aspx


post(Url,getParams()).then(res=>{
    console.log(res.data)
})
//以form表单形式提交post请求，post请求体中包含了应用级参数和系统级参数

function getParams(){
    //请求接口指令
    const RequestType  = '1002';//免费即时查询接口指令1002/在途监控即时查询接口指令8001/地图版即时查询接口指令8003
    // 组装应用级参数
    const RequestData = {
        'CustomerName': '',
        'OrderCode': '',
        'ShipperCode': 'YTO',
        'LogisticCode': 'YT00003618100',
    };
    const DataSign = Buffer.from(md5Hex(JSON.stringify(RequestData)+ApiKey)).toString('base64')
    const reqParams = {
        RequestType,
        EBusinessID,
        DataSign,
        RequestData:JSON.stringify(RequestData),
        DataType:2
    }
    return reqParams
}// 组装系统级参数

async function post(url,data){
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    const res = await axios.post(url,querystring.stringify(data))
    return res
}



